import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { message } from 'ant-design-vue';

import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api';
import { getAllMenusApi } from '#/api/core/menu';
import type { AuthApi } from '#/api/core/auth';
import { $t } from '#/locales';

// 定义后端用户数据接口
interface BackendUserInfo {
  id: number;
  username: string;
  nickname?: string;
  avatar?: string;
  email?: string;
  phone?: string;
  status?: number;
  lastLoginAt?: string;
  lastLoginIP?: string;
}

// 获取CSRF令牌
async function fetchCSRFToken() {
  try {
    console.log('开始获取CSRF令牌...');
    // 导入ensureCSRFToken函数
    const { ensureCSRFToken } = await import('#/api/request');
    const token = await ensureCSRFToken();
    console.log('CSRF令牌获取状态:', token ? '成功' : '失败');
    return token;
  } catch (error) {
    console.error('获取CSRF令牌失败:', error);
    return null;
  }
}

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  // 登录
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void>,
  ) {
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;

      // 确保在登录前获取CSRF令牌
      await fetchCSRFToken();

      // 提示用户正确的登录凭据
      if (params.username !== 'admin') {
        message.warning('请使用默认管理员账号：admin / 123456');
      }

      console.log('登录参数:', params);

      // 使用API客户端登录
      try {
        console.log('开始发送登录请求...');
        
        // 使用loginApi进行登录
        const result = await loginApi(params);
        console.log('登录响应:', result);
        
        if (result && result.accessToken) {
          accessStore.setAccessToken(result.accessToken);
          // 同时保存到localStorage，确保可以在其他地方获取
          localStorage.setItem('accessToken', result.accessToken);
          console.log('保存token到localStorage:', result.accessToken);

          // 如果登录接口返回了用户信息，直接使用
          if (result.user) {
            userInfo = convertUserInfo(result.user);
            userStore.setUserInfo(userInfo);
          } else {
            // 否则获取用户信息
            userInfo = await fetchUserInfo();
          }

          // 获取用户权限码
          const accessCodes = await getAccessCodesApi();
          accessStore.setAccessCodes(accessCodes);
          
          // 强制获取菜单数据
          console.log('登录成功，强制获取菜单数据...');
          try {
            const menus = await getAllMenusApi();
            console.log('强制获取的菜单数据:', menus);
          } catch (error) {
            console.error('强制获取菜单数据失败:', error);
          }

          if (accessStore.loginExpired) {
            accessStore.setLoginExpired(false);
          } else if (userInfo) {
            onSuccess
              ? await onSuccess?.()
              : await router.push(
                  userInfo.homePath || preferences.app.defaultHomePath,
                );
          }

          if (userInfo?.realName) {
            notification.success({
              description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
              duration: 3,
              message: $t('authentication.loginSuccess'),
            });
          }
        }
      } catch (error: any) {
        console.error('登录失败:', error);
        
        // 显示错误消息
        if (error.response && error.response.data) {
          notification.error({
            message: '登录失败',
            description: error.response.data.message || '用户名或密码错误',
            duration: 4,
          });
        } else {
          notification.error({
            message: '登录请求失败',
            description: '请检查网络连接',
            duration: 4,
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return userInfo;
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);
    // 清除localStorage中的token
    localStorage.removeItem('accessToken');
    console.log('已清除localStorage中的token');

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
    
    // 登出后刷新CSRF令牌
    await fetchCSRFToken();
  }

  // 将后端用户数据转换为前端需要的格式
  function convertUserInfo(backendUser: BackendUserInfo): UserInfo {
    return {
      userId: backendUser.id.toString(),
      username: backendUser.username,
      realName: backendUser.nickname || backendUser.username,
      avatar: backendUser.avatar || '',
      desc: '',
      homePath: '/dashboard',
      roles: [],
      token: accessStore.accessToken || '',
    };
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    try {
      // 获取用户信息
      const userData = await getUserInfoApi() as unknown as BackendUserInfo;
      
      // 将后端用户数据转换为前端需要的格式
      userInfo = convertUserInfo(userData);
      
      userStore.setUserInfo(userInfo);
    } catch (error) {
      console.error('Failed to fetch user info:', error);
    }
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
